package com.yytek.common.client.config;

import com.yytek.common.client.base.MqConfig;
import com.yytek.common.client.net.IotMqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class MQClientConfiguration {

	@Autowired
	private MqttConfig mqttConfig;

	@Value("${server.port}")
	private int serverPort;

	@Bean
	@SuppressWarnings(value = { "unchecked", "rawtypes" })
	public IotMqttClient iotMqttClient() {
		IotMqttClient client= new IotMqttClient();
		MqConfig config = new MqConfig();
		config.setBroker(mqttConfig.getBroker());
		config.setPassword(mqttConfig.getPassword());
		config.setUserName(mqttConfig.getUserName());
		//获取当前服务ip和端口
		InetAddress address = null;
		try {
			 address = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		String clientId=mqttConfig.getClientId() +address.getHostAddress()+serverPort;
		config.setClientId(clientId);
		client.init(config);

		return client;
	}
}
